package vn.com.fsoft.model.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.classic.Session;

import vn.com.fsoft.model.dao.IContactDAO;
import vn.com.fsoft.model.entities.Contact;
import vn.com.fsoft.utility.HibernateUtils;

public class ContactDAO extends HibernateUtils implements IContactDAO {

	Session session;
	public ContactDAO(){
		session = getSessionFactory().openSession();
	}
	
	@Override
	public List<Contact> getAllContact(int pageSize, int currentPage) {
		//Session session = getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery("from Contact");
		query.setFirstResult(pageSize * (currentPage - 1));
		query.setMaxResults(pageSize);
		List<Contact> listContact = query.list();
		session.getTransaction().commit();
		closeSession(session);
		return listContact;
	}

	@Override
	public boolean addNewContact() {
		return false;
	}

	@Override
	public boolean updateContact() {

		return false;
	}

	@Override
	public long countContact() {
		Session session = getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery("select count(*) from Contact");
		long count = Long.parseLong(query.uniqueResult().toString());
		session.getTransaction().commit();
		closeSession(session);
		return count;
	}
	
	@Override
	public List<Contact> lookUpContact(String fName, String sName,int pageSize,int currentPage) {
		try {
			if(fName==null || sName==null)
				return null;			
			session.getTransaction().begin();
			String sql = "from Contact where 1=1";
			if(fName.length()>0)
				sql+=" and lower(firstName) like :fName" ;
			if(sName.length()>0){
				sql+=" and lower(surName) like :sName";
			}
			Query query = session.createQuery(sql);
			if(fName.length()>0){
				fName = "%"+fName.toLowerCase()+"%";
				query.setParameter("fName", fName);
			}
			if(sName.length()>0){
				sName = "%"+sName.toLowerCase()+"%";
				query.setParameter("sName", sName);
			}
			query.setFirstResult(pageSize * (currentPage - 1));
			query.setMaxResults(pageSize);
			List<Contact> list = query.list();
			session.flush();
			session.getTransaction().commit();
			return list;
		} catch (Exception e) {
			if (session.getTransaction().isActive()) {
				session.getTransaction().rollback();
			}
		}
		return null;
	}	
}
